/**
 * WebSocket 相关路由
 * 提供 WebSocket 状态查询和管理接口
 */

const express = require('express');
const router = express.Router();

/**
 * 获取 WebSocket 服务状态
 */
router.get('/status', (req, res) => {
    const wsService = req.app.locals.wsService;
    
    if (!wsService) {
        return res.status(500).json({
            success: false,
            message: 'WebSocket 服务未初始化'
        });
    }

    res.json({
        success: true,
        data: {
            clientCount: wsService.getClientCount(),
            clients: wsService.getClients(),
            timestamp: new Date().toISOString()
        }
    });
});

/**
 * 广播消息给所有客户端
 */
router.post('/broadcast', (req, res) => {
    const wsService = req.app.locals.wsService;
    const { message, type = 'notification' } = req.body;

    if (!wsService) {
        return res.status(500).json({
            success: false,
            message: 'WebSocket 服务未初始化'
        });
    }

    if (!message) {
        return res.status(400).json({
            success: false,
            message: '消息内容不能为空'
        });
    }

    wsService.broadcast({
        type: type,
        content: message,
        from: 'server'
    });

    res.json({
        success: true,
        message: '消息已广播',
        data: {
            clientCount: wsService.getClientCount(),
            timestamp: new Date().toISOString()
        }
    });
});

/**
 * 发送消息给指定客户端
 */
router.post('/send', (req, res) => {
    const wsService = req.app.locals.wsService;
    const { clientId, message, type = 'notification' } = req.body;

    if (!wsService) {
        return res.status(500).json({
            success: false,
            message: 'WebSocket 服务未初始化'
        });
    }

    if (!clientId || !message) {
        return res.status(400).json({
            success: false,
            message: '客户端ID和消息内容不能为空'
        });
    }

    const success = wsService.sendToClient(clientId, {
        type: type,
        content: message,
        from: 'server',
        timestamp: new Date().toISOString()
    });

    if (success) {
        res.json({
            success: true,
            message: '消息已发送',
            data: {
                clientId: clientId,
                timestamp: new Date().toISOString()
            }
        });
    } else {
        res.status(404).json({
            success: false,
            message: '客户端不存在或连接已断开'
        });
    }
});

/**
 * 获取在线客户端列表
 */
router.get('/clients', (req, res) => {
    const wsService = req.app.locals.wsService;
    
    if (!wsService) {
        return res.status(500).json({
            success: false,
            message: 'WebSocket 服务未初始化'
        });
    }

    res.json({
        success: true,
        data: {
            clients: wsService.getClients(),
            count: wsService.getClientCount(),
            timestamp: new Date().toISOString()
        }
    });
});

module.exports = router;
